package com.fourth.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fourth.dao.UserDao;
import com.fourth.service.UserService;
import com.fourth.util.SMSUtil;
import com.ljx.entity.UserInfo;
import com.ljx.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author LJX
 * @Description: TODO
 * @Date: 2023/3/1 16:03
 * @Version 1.0
 */
@RestController
@RequestMapping("/system/user")
public class UserController {
	@Autowired(required = false)
	private UserDao userDao;

	@Autowired
	private UserService userService;


	@Autowired
	private StringRedisTemplate redisTemplate;

	@GetMapping("/getByTel/{telephone}")
	public UserInfo getByTel(@PathVariable String telephone){
		QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
		wrapper.eq("telephone",telephone);
		UserInfo userInfo = userDao.selectOne(wrapper);
		return userInfo;
	}

	/**
	 * 手机验证码，将信息传到redis中
	 * @param phone
	 * @return
	 */
	@RequestMapping("sms")
		public Result sms(String phone){
		String s = SMSUtil.smsVerification(phone);
		System.out.println(s);
		redisTemplate.opsForValue().set(s,"",5, TimeUnit.MINUTES);
		return new Result(2000,"发送成功",s);

	}

	/**
	 * 注册用户信息
	 */
	@RequestMapping("signInsert")
	public Result registUser(String telephone,String password){

		// 将密码加密存入数据库
		BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
		String encode = bCryptPasswordEncoder.encode(password);
		UserInfo userInfo = new UserInfo();
		userInfo.setTelephone(telephone);
		userInfo.setPassword(encode);
		int insert = userDao.insert(userInfo);
		if (insert>0){
			return new Result(2000,"用户注册完成",null);
		}
		return new Result(5000,"用户注册失败",null);
	}


	/**
	 * 用户密码修改
	 * @return
	 */
	@RequestMapping("/updatePassword/{telephone}/{newPassword}")
	public Result updatePassword(@PathVariable("telephone") String telephone ,@PathVariable("newPassword") String newPassword){

		return userService.updatePassword(telephone,newPassword);
	}
}
